<template>
  <div>
    <!-- <span class="tinyTitle">
      <div class="titleFlag"></div>
      {{ "地区薪酬前十" }}
      <span class="titleTips">数据来源于{{companyNum}}样本，结果仅供参考</span>
    </span> -->
    <el-row class="search-container">
      <el-form ref="form" label-width="auto">
        <el-form-item label="统计时间：">
          <el-date-picker
            v-model="selectBetweenTime"
            :clearable="false"
            size="small"
            type="monthrange"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            :picker-options="pickerOptions"
            @change="handleDateChange"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </el-row>
    <div class="h100" ref="line_echartDom"></div>
  </div>
</template>

<script>
import { chartTop10Salary } from "@/api/salary";
export default {
  name: "regionBarChart",
  props: {
    regionBarDescAvg: {
      type: String,
      default: 0,
    },
    chartDataIsNotEmpty: {
      type: Boolean,
      default: true,
    },
    hoverValue: {
      type: String,
      default: "0",
    },
    hoverName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      companyNum: "2365",
      resData: [],
      chartData: {},
      selectBetweenTime: [],
      pickerMinDate: "",
      firstDayofLastMonth: "",
      pickerOptions: {
        disabledDate: (time) => {
          const nowTime = time.getTime();
          if (nowTime < 1672502400000 || nowTime > this.firstDayofLastMonth) {
            return true;
          }
          if (this.pickerMinDate) {
            const monthsDiff =
              Math.abs(nowTime - this.pickerMinDate) /
              (1000 * 60 * 60 * 24 * 30);
            // 如果相差的月份大于6个月，则禁用该日期
            return monthsDiff > 6 || nowTime < 1672502400000;
          }
        },
        onPick: (obj) => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
      },
    };
  },
  computed: {
    isLabelShow() {
      return this.$store.state.chart.isLabelShow;
    },
  },
  created() {
    // 创建一个表示当前日期的 Date 对象
    var currentDate = new Date();

    // 将当前日期设置为本月的第一天
    currentDate.setDate(1);

    // 将当前日期减去一天，得到上个月最后一天
    currentDate.setDate(0);

    // 设置时间为零点
    currentDate.setHours(0, 0, 0, 0);

    // 获取时间戳
    var timestamp = currentDate.getTime();

    this.firstDayofLastMonth = timestamp;
  },
  mounted() {
    //默认显示上上月日期
    // let date = new Date(new Date() - 31 * 24 * 3600 * 1000);
    let date = new Date();
    let currentMonth = date.getMonth() + 1;
    let value =
      date.getFullYear() +
      "-" +
      (currentMonth < 10 ? "0" : "") +
      currentMonth +
      "-" +
      "01";

    // 默认显示上月日期
    let date1 = new Date();
    date1.setMonth(date1.getMonth() - 6); // 减去6个月
    let previousMonth = date1.getMonth() + 1;
    let value1 =
      date1.getFullYear() +
      "-" +
      (previousMonth < 10 ? "0" : "") +
      previousMonth +
      "-" +
      "01";

    // 确保selectBetweenTime中的日期按照从小到大的顺序排列
    this.selectBetweenTime = [value, value1].sort();
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
      };
      // params.beginTime = "2023-1-1";
      // params.endTime = "2023-5-1";
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.beginTime = this.selectBetweenTime[0];
        params.endTime = this.selectBetweenTime[1];
        // params.beginTime = "2023-1-1";
        // params.endTime = "2023-5-1";
      }
      chartTop10Salary(params).then((response) => {
        // console.log("chartTop10Salary--------------->",response.data.list);
        this.$emit("update:regionBarDescAvg", response.data.salaryNum);
        this.chartData = this.handleData(response.data.list);
        if (this.chartData.city.length == 0) {
          this.$emit("update:chartDataIsNotEmpty", false);
        }
        console.log(
          "----chartTop10Salary-----11111-------->chartData",
          this.chartData
        );
        setTimeout(() => {
          this.init();
        }, 500);
      });
    },
    handleData(data) {
      // 降序
      // //console.log("handleData", data);

      // data.sort((a, b) => {
      //   return b.salaryNum - a.salaryNum;
      // });
      let dataArr = {
        city: [],
        salary: [],
      };
      data.forEach((element) => {
        dataArr.city.push(element.salaryRegionName);
        dataArr.salary.push(element.average);
      });

      return dataArr;
    },
    init() {
      if (!this.$refs["line_echartDom"]) return;
      this.myChart = this.$echarts.init(this.$refs["line_echartDom"]);
      let city = this.chartData.city,
        salary = this.chartData.salary;
      let option = {
        xAxis: {
          type: "category",
          data: city,
          name: "(城市)",
          interval: 0,
          // boundaryGap: false,
          axisLabel: {
            formatter(val) {
              // 当字符串长度超过2时
              if (val.length > 2) {
                // 把字符串分割成字符串数组
                const array = val.split("");
                const index = array.indexOf("市");
                //在下标2处删除0个，加上回车
                array.splice(index, 1);
                return array.join("");
              } else {
                return val;
              }
            },
            color: "#8193B2",
            fontSize: "13px",
          },
          axisLine: {
            lineStyle: {
              color: "#E4EDF8",
            },
          },
          nameTextStyle: {
            lineHeight: 30, //标题行高
            color: "#8193B2",
            verticalAlign: "top", //标题位置
            padding: [0, 0, 0, 0], // 上右下左与原位置距离
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            lineStyle: {
              color: "#000000",
            },
          },
          backgroundColor: "#1B78FF",
          borderColor: "#1B78FF",
          textStyle: {
            color: "#fff",
          },
          formatter: (params) => {
            const content = params[0];
            return `月收入平均值 ¥${content.value}`;
          },
          // position: ["50%", 0],
        },
        grid: {
          right: "50",
          bottom: "50",
          top: "50",
          left: "50",
        },
        yAxis: {
          type: "value",
          // scale: true,
          name: "(薪酬 元)",
          axisLabel: {
            color: "#8193B2",
            fontSize: "12px",
          },
          axisLine: {
            lineStyle: {
              color: "#E4EDF8",
            },
          },
          nameTextStyle: {
            padding: [0, 45, 10, 0], // 上右下左与原位置距离

            color: "#8193B2",
          },
        },
        series: [
          {
            data: salary,
            type: "bar",
            showBackground: false,
            barWidth: "18px",
            label: {
              show: this.isLabelShow,
              position: "top",
            },
            itemStyle: {
              normal: {
                color: this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  {
                    //只要修改前四个参数就ok
                    offset: 0,
                    color: "#81B4FF",
                  }, //柱图渐变色
                  {
                    offset: 1,
                    color: "#A3DBFF",
                  },
                ]),
                borderRadius: [4, 4, 0, 0],
              },
            },
            emphasis: {
              itemStyle: {
                color: {
                  type: "linear",
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: "#0068FF", // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#4996FF", // 100% 处的颜色
                    },
                  ],
                  global: false, // 缺省为 false
                },
              },
            },
          },
        ],
      };
      this.myChart.on("mouseover", (params) => {
        this.$emit("update:hoverValue", params.value + "");
        this.$emit("update:hoverName", params.name);
      });
      option && this.myChart.setOption(option);
      window.addEventListener("resize", () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: 1,
      });
      this.$emit("update:hoverValue", this.chartData.salary[1]);
      this.$emit("update:hoverName", this.chartData.city[1]);
    },
    handleDateChange(val) {
      this.pickerMinDate = null;
      this.fetchData();
    },
  },
};
</script>

<style lang="scss" scoped>
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  margin-top: 16px;
  color: #222;
  font-weight: bold;
  margin-bottom: 22px;
  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
  .titleTips {
    display: flex;
    align-items: center;
    color: #999999;
    font-size: 14px;
    font-weight: normal;
    margin-left: 8px;
  }
}
.search-container {
  height: 40px;
}
.h100 {
  width: 100%;
  height: 16vw;
  min-width: 615px;
  min-height: 280px;
}
::v-deep .el-date-editor {
  background: #fafcfe;
  border-radius: 4px;
  border: 1px solid #e4edf8;
}
::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #555555;
  line-height: 22px;
}
::v-deep .el-form-item {
  margin-bottom: 0px;
}
::v-deep .el-form-item__label-wrap {
  margin-left: 0px !important;
  padding-top: 6px;
}
</style>
